#pragma once
#include "Common.hpp"
#include <iostream>
#include <string>
#include <fstream> //c++的文件操作

const std::string gdictname = "dict.txt";
const std::string gpath = "./";
const std::string gsep = ":";

class Dict
{
private:
    bool LoadDictionary()
    {
        std::string file = _path + _filename;
        std::ifstream in(file.c_str());
        if (!in.is_open())
        {
            std::cout << "打开失败" << std::endl;
            return false;
        }
        std::string line;
        while (std::getline(in, line)) // 因为while所以getline的返回值会隐式转换成bool类型，而且istream又重载了bool运算符所以就可以判断了
        {
            std::string key_left;
            std::string value_right;
            if (SpilyString(line,&key_left, &value_right, gsep))
            {
                // _dictionary.insert(std::make_pair(key,value));
                _dictionary.emplace(key_left, value_right);
            }
        }
        in.close();
        return true;
    }
public:
    Dict(const std::string &path = gpath, const std::string &filename = gdictname)
        : _path(path), _filename(filename)
    {
        LoadDictionary();
        Print();
    }

    std::string Translate(const std::string &word)
    {
        auto iter=_dictionary.find(word);
        if(iter==_dictionary.end())return "没有这个单词";
        return iter->second;
    }
    void Print()
    {
        for(auto &e:_dictionary)
        {
            std::cout<<e.first<<" : "<<e.second<<std::endl;
        }
    }
    ~Dict()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dictionary;
    std::string _path;
    std::string _filename;
};
